package cn.swing.ushare.guestbook.webapi.service.impl;

import cn.swing.ushare.common.ex.ServiceException;
import cn.swing.ushare.common.web.State;
import cn.swing.ushare.guestbook.service.IGuestbookService;
import cn.swing.ushare.guestbook.webapi.mapper.GuestbookMapper;
import cn.swing.ushare.pojo.vo.FeedBackVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class GuestbookService implements IGuestbookService {
    @Autowired
    GuestbookMapper mapper;

    @Override
    public List<FeedBackVO> list(Integer page, String feedbackPeople) {
        return mapper.list(page, feedbackPeople);
    }


    @Override
    public Integer deleteByIds(Integer[] ids) {
        List<String> nicknames = new ArrayList<>();
        for (Integer id : ids) {
            nicknames.add(mapper.selectNicknameById(id));
        }
        Integer rows = mapper.deleteByIds(ids);
        if (rows == 0) {
            throw new ServiceException(State.ERR_GUESTBOOK_DELETE, "删除失败,反馈不存在");
        } else {
            for (String nickname : nicknames) {
                mapper.insertOperationLog("反馈管理", "删除", logOperation(), "删除用户: '" + nickname + "'的反馈");
            }
            return rows;
        }
    }

    @Override
    public Integer count(String feedbackPeople) {
        return mapper.count(feedbackPeople);
    }

    @Override
    public Integer countAllGuestbook() {
        mapper.deleteOperationLog();
        return mapper.countAllGuestbook();
    }


    @Override
    public String feedbackComment(String type, Integer commentId, Integer userId, String reason) {
        String nickname = mapper.selectUserNicknameById(userId);
        String content = mapper.selectCommentContentById(commentId);
        mapper.insertFeedback(type, content, nickname, logOperation(), reason);
        return "反馈成功";
    }

    // 日志操作
    private String logOperation() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = (String) principal;
        return username;
    }


    @Override
    public String feedbackArticle(String type, String title, Integer userId, String reason) {
        String nickname = mapper.selectUserNicknameById(userId);
        mapper.insertFeedback(type,title,nickname,logOperation(),reason);
        return null;
    }
}
